package com.moore.Servlet;

import com.alibaba.fastjson2.JSON;
import com.moore.net.HttpRequest;
import com.moore.net.HttpResponse;
import com.moore.net.HttpServlet;
import com.moore.utils.AddressUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class AddressServlet extends HttpServlet {

    @Override
    public byte[] doGet(HttpRequest request, HttpResponse response) {
        String responseData = "";
        String type = request.getParams().get("type");
        String address;
        try {
            address = URLDecoder.decode(request.getParams().get("address"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String userId = request.getParams().get("userId");
        switch (type) {
            case "get":
                responseData = JSON.toJSONString(AddressUtils.getAddress(userId));
                break;
            case "insert":
                responseData = AddressUtils.insertAddress(address, userId);
                break;
            case "update":
                String oldAddress;
                try {
                    oldAddress = URLDecoder.decode(request.getParams().get("oldAddress"),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                responseData = AddressUtils.updateAddress(address, oldAddress);
                break;
            case "delete":
                responseData = AddressUtils.deleteAddress(address, userId);
                break;
        }
        return responseData.getBytes();
    }
}
